/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DBL;

import MDL.*;
import java.sql.*;

/**
 *
 * @author Peter
 */
public class DBKunde implements IFDBKunde
{

    Connection con;

    public DBKunde()
    {
        con = DBConnection.getInstance().getDBcon();
    }

    public int createKunde(Kunde kun)
    {
        int kundeId = GetMax.getNextID("SELECT MAX(kundeId) FROM kunde");
        kundeId++;

        int rc = -1;
        String query = "INSERT INTO kunde(kundeId, tlfnr, kundenavn, adresse, postnummer) VALUES(" + kundeId + "," + kun.getTlfnr() + ",'" + kun.getKundenavn() + "','" + kun.getAdresse() + "','" + kun.getPostnummer() + "')";

        System.out.println(query);
        try
        {
            Statement state = con.createStatement();
            state.setQueryTimeout(5);
            rc = state.executeUpdate(query);
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR:" + e);
        }
        System.out.println(rc);
        return rc;
    }  

    public int updateKunde(Kunde kun)
    {
        int rc = -1;

        String query = "UPDATE Kunde SET " +
                "kundenavn ='" + kun.getKundenavn() + "'," +
                "adresse ='" + kun.getAdresse() + "', " +
                "postnummer ='" + kun.getPostnummer() + "', " +
                "WHERE tlfnr = " + kun.getTlfnr();

        System.out.println(query);
        try
        {
            Statement state = con.createStatement();
            state.setQueryTimeout(5);
            rc = state.executeUpdate(query);
       //     state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR: " + e);
        }
        return rc;
    }

    public Kunde findKunde(int tlfnr, Kunde kun)
    {
        int kundeId = 0;
        ResultSet results;

        String query = "SELECT kundenavn, adresse, postnummer FROM kunde WHERE tlfnr = " + tlfnr + "";
        try
        {
            Statement state = con.createStatement();
            results = state.executeQuery(query);
            if (results.next())
            {
                kun.setKundenavn(results.getString(1));
                kun.setAdresse(results.getString(2));
                kun.setPostnummer(results.getString(3));
                
                System.out.println(kun.getKundenavn());
            }
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR: " + e);
        }
        return kun;
    }

    public void deleteKunde(int tlfnr)
    {
        String query = "DELETE FROM kunde WHERE tlfnr = " + tlfnr + "";
        try
        {
            Statement state = con.createStatement();
            state.executeUpdate(query);
            state.close();
        } catch (Exception e)
        {
            System.out.println("ERROR: " + e);
        }
    }
}
